<template>
	<view>
		<cu-custom :key="'header'+headerKey" bgColor="bg-gradual-blue-light" :isBack="true" backText="返回" title="签到"></cu-custom>
		<zh-text labelAlign="left" label="当前位置" labelWidth="150rpx" :value="curLocation"  :rightIconClass="locationError?'basefont icon-reload text-red':'basefont icon-location text-blue'" @right-icon-click="gotoSearch" ></zh-text>
		
		<view style="width: 100% ;height: 22.4em;">
			<!--#ifdef MP-WEIXIN -->
			<map id="navi_map" :longitude="longitude" :latitude="latitude" scale="15" :markers="markers" style="width: 100%;height: 100%;" ></map>
			<!--#endif -->
			<!--#ifdef H5 -->
			<Amap ref="mapView" mapHeight="22.4em" @change="mapChange"></Amap>
			<!--#endif -->
		</view>
		<view class="cu-form-group" style="justify-content:center">
		<view class="text-gray text-sm text-center bg-white" @tap="refresh">
			刷新当前位置<text style="padding-left: 10rpx;" class="basefont icon-reload"></text>
		</view>
		</view>
		<zh-input type="textarea" labelAlign="left" label="备注" labelWidth="100rpx" v-model="remarks"  placeholder="签到备注信息"  ></zh-input>
		
		<view class="text-center bg-white">
			<button class="cu-btn round  shadow margin-tb-sm" @tap="signIn" :class="signInBg">
				<view>
				<view style="font-size: 36rpx;">{{text}}</view>
				<view style="font-size: 28rpx;" v-if="canSignIn">{{currentTime.substr(0,12)}}</view>
				<view style="font-size: 28rpx;" v-if="canSignIn">{{currentTime.substr(12)}}</view>
				<view style="font-size: 28rpx;" v-if="!canSignIn">{{signInTime.substr(0,12)}}</view>
				<view style="font-size: 28rpx;" v-if="!canSignIn">{{signInTime.substr(12)}}</view>
				</view>
			</button>
		</view>
		<view class="flex flex-direction bg-white" style="padding: 20rpx 20rpx 20rpx 20rpx">
			<button style="width: 100%;height: 100rpx;" class="cu-btn shadow margin-tb-sm lg bg-gradual-blue-light"  @tap="signInRecord">签到记录</button>
		</view>
		<u-modal v-model="modelShow"  :content="modelContent" confirm-color="#0081ff" @confirm="modelConfirm"></u-modal>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import store from '@/store';
	// #ifdef MP-WEIXIN
	import amap from '@/common/amap-wx.js';
	// #endif
	// #ifdef H5
	import Amap from '@/pages/system/map/h5LocationMap.vue'
	// #endif
	import systemConfig from '@/common/config/systemConfig.js'
	import miment from 'miment'
	import api from '@/api/society/home/signIn.js'
	export default {
		onShow() {
			this.headerKey += 1;
		},
		components: {
			// #ifdef H5
			Amap
			// #endif
		},
		data() {
			return {
				headerKey:0,
				curLocation:"定位中",
				locationError:false,
				markers: [],
				latitude:null,
				longitude:null,
				locationData:{},
				amapPlugin: null,
				modelType:'',
				modelShow:false,
				modelContent:'功能目前在测试中，尚未开放',
				timer: '', //定义一个定时器的变量
				canSave:false,
				canSignIn:true,
				signInBg:'bg-gradual-blue-light',
				text:'签到',
				remarks:'',
				currentTime: miment().format('YYYY年MM月DD日 hh:mm:ss'), // 获取当前时间
				signInTime:'',
				signInTimer: '',
				daojishi:300
			}
		},
		onLoad: function (option) {
			// #ifdef MP-WEIXIN
			this.amapPlugin = new amap.AMapWX({
				key: systemConfig.amapKey
			});
			// #endif
			var vm = this;
			vm.timer = setInterval(() => {
				vm.currentTime = miment().format('YYYY年MM月DD日 hh:mm:ss');
			}, 1000);
			
		},
		onReady() {
			// #ifdef MP-WEIXIN
			this.isGetLocation()
			// #endif
			const hhCache = getApp().globalData.hhCache;
			// 设置缓存 且设置时间
			const successData = hhCache.get("sign_in_clock")
			if(successData&&successData.success){
				this.signInBg = 'bg-gray'
				this.text = successData.text
				this.canSignIn = false
				this.signInTime = successData.time
				let timestamp = Date.parse(new Date())
				let daojishi = 300-(timestamp-successData.timestamp)/1000
				// 倒计时开始
				const vm =this
				if(daojishi&&daojishi>0){
					this.signInTimer = setInterval(function() {
						daojishi--;
						if (daojishi <= 0) {
							vm.canSignIn = true
							vm.signInBg = 'bg-gradual-blue-light'
							vm.text = '签到'
							hhCache.remove("sign_in_clock")
							clearInterval(vm.signInTimer);
						}
					}, 1000);
				}
				
			}
		},
		methods: {
			gotoSearch(){
				if(this.locationError){
					// #ifdef MP-WEIXIN
					this.isGetLocation()
					// #endif
				}
			},
			modelConfirm(){
				if(this.modelType == 'auth'){
					this.$Router.back(1)
				}
			},
			signIn(){
				const hhCache = getApp().globalData.hhCache;
				
				const successData = hhCache.get("sign_in_clock")
				// 设置缓存 且设置时间
				if(successData&&successData.success){
					this.$refs.uToast.show({
						title: "已成功签到，5分钟内请不要重复签到",
						// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
						type: 'warning', 
						position:'top',
						// 如果不需要图标，请设置为false
						icon: true,
						duration:4000
					})
					return
				}
				if(this.canSave){
					const vm = this;
					const regeocodeData = this.locationData.regeocodeData
					const data={}
					data.locationAddress=regeocodeData.formatted_address
					data.latitude=this.locationData.latitude
					data.longitude=this.locationData.longitude
					data.remarks = this.remarks
					data.signInRules='3'
					data.signInType='common'
					const addressComponent =regeocodeData.addressComponent
					if(addressComponent){
						data.provinceCode=''
						data.provinceValue=addressComponent.province
						data.cityCode=''
						data.cityValue=addressComponent.city
						data.countyCode = addressComponent.adcode
						data.countyValue = addressComponent.district
						data.townCode = addressComponent.towncode
						data.townValue =addressComponent.township
					}
					this.$http.post(api.add, data).then(res => {
						let type ='warning'
						if(res.result.success=='1'){
							type ='success'
							// 设置缓存 且设置时间
							this.text = '已签到'
							this.signInTime = this.currentTime
							hhCache.put("sign_in_clock",{success:true,text:this.text,time:this.signInTime, timestamp:Date.parse(new Date())},300);
							this.canSignIn = false
							this.signInBg = 'bg-gray'
							// 倒计时开始
							let daojishi = 300
							this.signInTimer = setInterval(function() {
								daojishi--;
								if (daojishi <= 0) {
									vm.canSignIn = true
									vm.signInBg = 'bg-gradual-blue-light'
									vm.text = '签到'
									hhCache.remove("sign_in_clock")
									clearInterval(vm.signInTimer);
								}
							}, 1000);
						}
						this.$refs.uToast.show({
							title: res.result.msg,
							// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
							type: type, 
							position:'top',
							// 如果不需要图标，请设置为false
							icon: true,
							duration:4000
						})
						
					}).catch(error => {
						
					})
				}else{
					this.modelContent='未定位成功，不能签到'
					this.modelShow=true
				}
			},
			signInRecord(){
				this.$Router.push({
					name: 'signInRecords'
				});
			},
			// #ifdef H5
			mapChange(data){
				this.locationData = data
				if(data&&data.latitude&&data.longitude&&data.regeocodeData.formatted_address){
					this.curLocation = data.regeocodeData.formatted_address
					this.latitude=data.latitude
					this.longitude=data.longitude
					this.canSave = true
				}else{
					this.curLocation = '定位失败'
				}
				console.log(data)
			},
			// #endif
			refresh(){
				// #ifdef MP-WEIXIN
				this.isGetLocation()
				// #endif
				// #ifdef H5
				this.$refs.mapView.h5Geolocation()
				// #endif
			},
			// #ifdef MP-WEIXIN
			getRegeo(){
				const that = this;
				this.amapPlugin.getRegeo({
					success: (data) => {
						if(data){
							this.locationData = data[0]
							const regeocodeData=data[0].regeocodeData
							if(regeocodeData){
								this.curLocation = regeocodeData.formatted_address
								this.latitude=data[0].latitude
								this.longitude=data[0].longitude
								this.canSave = true
								const  marker={}
								marker.id =0
								marker.latitude=data[0].latitude
								marker.longitude=data[0].longitude
								marker.width=23
								marker.height=33
								this.markers.push(marker)
							}
						}
					},
					fail:(info)=> {
						this.curLocation = '定位失败'
					}
				});
				
			},
			isGetLocation(a="scope.userLocation"){ // 3. 检查当前是否已经授权访问scope属性，参考下截图
				var _this=this;
				uni.getSetting({
					success(res) {	
						const authFlag=res.authSetting[a]
						if (!authFlag) {  //3.1 每次进入程序判断当前是否获得授权，如果没有就去获得授权，如果获得授权，就直接获取当前地理位置
							if(authFlag==null||authFlag==undefined){
								_this.getRegeo(this)
							}else{
								wx.showModal({
								    title: '提示',
								    content: '需要获取您的位置信息，用于签到',
								    cancelText:'不授权',
								    cancelColor:'#999',
								    confirmText:'授权',
								    confirmColor:'#0081ff',
								    success(res) {
								        if (res.confirm) {
								            uni.openSetting({
								                success(res) {
													_this.getRegeo(this);
								                },
												fail(res) {
													_this.$Router.back(1)
												}
								            })                                
								        } else if (res.cancel) {
								            _this.getRegeo(this)
								        }
								    }
								})
							}
						}else{
							_this.getRegeo(this)
						}
					}
				});
			}
			// #endif
		},
		beforeDestroy() {
			if (this.timer) {
				clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
			}
			if (this.signInTimer) {
				clearInterval(this.signInTimer); // 在Vue实例销毁前，清除我们的定时器
			}
		}
		
	}
</script>

<style>
	.cu-btn {
		display: inline-flex;
		text-align: center;
		justify-content: center;
		align-items: center;
		width: 288rpx;
		height: 288rpx;
	}
	
</style>
